const fs = require('fs');
const path = require('path');
const { spawnSync } = require('child_process');

let originalContent = '';
const routerPath = path.join(__dirname, '../src/router');
const srcPath = path.join(__dirname, '../src');
const indexTsPath = path.join(__dirname, '../src/index.ts');


spawnSync('cls', {
  stdio: 'inherit',  // 继承父进程的stdio
  shell: true        // 兼容Windows环境
});

const autoImportRoute = () => {

  // 读取原文件内容
  originalContent = fs.existsSync(indexTsPath)
    ? fs.readFileSync(indexTsPath, 'utf-8')
    : '';

  const scanDirectory = (dir) => {
    const items = fs.readdirSync(dir);
    return items.flatMap(item => {
      const fullPath = path.join(dir, item);
      const stat = fs.statSync(fullPath);

      if (stat.isDirectory()) {
        return scanDirectory(fullPath);
      } else if (/\.(js|ts)$/.test(item)) {
        const relativePath = path.relative(routerPath, fullPath)
          .replace(/\\/g, '/')
          .replace(/\.(js|ts)$/, '');
        return `import './router/${relativePath}';`;
      }
      return [];
    });
  };

  const imports = scanDirectory(routerPath).join('\n');

  // 定义注释标记
  const startMarker = '// $_Auto_Import_start_';
  const endMarker = '// $_Auto_Import_end_';
  const regex = new RegExp(/\/\/ \$_Auto_Import_start_([\s\S]*?)\/\/ \$_Auto_Import_end_/);

  // 检查原内容是否已有标记
  const hasMarkers = originalContent.includes(startMarker) &&
    originalContent.includes(endMarker);


  let newContent;
  if (hasMarkers) {
    if (originalContent.match(regex)[0] == `${startMarker}\n${imports}\n${endMarker}`) {
      console.log('⏩ 无路由变更');
    } else {
      console.log('✅ 路由导入完成');

      // 替换标记之间的内容
      newContent = originalContent.replace(regex, `${startMarker}\n${imports}\n${endMarker}`);
      fs.writeFileSync(indexTsPath, newContent);
    }

  } else {
    // 添加新标记和导入内容
    newContent = `${startMarker}\n${imports}\n${endMarker}\n\n${originalContent}`;
    fs.writeFileSync(indexTsPath, newContent);
  }

};

autoImportRoute();
